package org.feng.navigation.listener;

import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

/**
 * 菌子Nacos配置监听器
 *
 * @version V1.0
 * @author: junzi
 * @date: 2023年02月03日 15时59分
 */
@Data
@Slf4j
@Configuration
public class JunZiNacosConfigListener {

    @Resource
    NacosConfigListenerProperties nacosConfigListenerProperties;
    private static final String GROUP = "junzi";

    @Resource
    private ConfigService configService;

    @PostConstruct
    private void init() throws NacosException {
        List<String> dataIdList = nacosConfigListenerProperties.getDataId();
        log.info("正在监听 group=junzi, nacos.listener.dataId={}", dataIdList);
        for (String dataId : dataIdList) {
            if (dataId.endsWith("yml")) {
                configService.addListener(dataId, GROUP, new DefaultNacosConfigListener());
                continue;
            }
            if (dataId.endsWith("json")) {
                configService.addListener(dataId, GROUP, new JsonFileNacosConfigListener<>(TestParse.class));
            }
        }
    }

    @Data
    @ConfigurationProperties("nacos.listener")
    public static class NacosConfigListenerProperties {
        private List<String> dataId;
    }

    @Data
    public static class TestParse {
        private Long code;
        private String reason;
        private Boolean success;
    }
}
